﻿using System.Linq.Expressions;
using Admin.ApplicationLib.Entities;
using Ardalis.Specification.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace Admin.ApplicationLib.Repositories
{
    public class RoleRepository : RepositoryBase<RoleEntity>, IRoleRepository
    {
        private readonly AdminApplicationDbContext _dbContext;

        public RoleRepository(AdminApplicationDbContext dbContext) : base(dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task EnsureCollectionLoadedAsync<TProperty>(RoleEntity entity,
            Expression<Func<RoleEntity, IEnumerable<TProperty>>> propertyExpression)
            where TProperty : class
        {
            await _dbContext.Entry(entity).Collection(propertyExpression).LoadAsync();
        }

        public async Task<IList<RoleClaimEntity>> QueryClaimsByRoleAsync(Guid id)
        {
            try
            {
                return await _dbContext.RoleClaims!.Where(i => i.RoleId == id).ToListAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task AddRoleClaimAsync(RoleClaimEntity roleClaimEntity)
        {
            await _dbContext.RoleClaims!.AddAsync(roleClaimEntity);
        }

        public Task RemoveRoleClaimAsync(RoleClaimEntity item)
        {
            _dbContext.RoleClaims!.Remove(item);

            return Task.CompletedTask;
        }

        public async Task<IList<UserRoleEntity>> QueryUserRolesByRoleAsync(Guid id)
        {
            return await _dbContext.UserRoles!.Where(i => i.RoleId == id)
                .ToListAsync();
        }

        public async Task AddUserRoleAsync(UserRoleEntity userRoleEntity)
        {
            await _dbContext.UserRoles!.AddAsync(userRoleEntity);
        }

        public Task RemoveUserRoleAsync(UserRoleEntity item)
        {
            _dbContext.UserRoles!.Remove(item);

            return Task.CompletedTask;
        }
    }
}